import datetime
import typing

from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
from sqlalchemy.orm.exc import DetachedInstanceError


class Base(DeclarativeBase):
    def repr(self, **fields: typing.Dict[str, typing.Any]) -> str:
        """
        Helper for __repr__
        """
        field_strings = []
        at_least_one_attached_attribute = False
        for key, field in fields.items():
            try:
                field_strings.append(f"{key}={field!r}")
            except DetachedInstanceError:
                field_strings.append(f"{key}=DetachedInstanceError")
            else:
                at_least_one_attached_attribute = True
        if at_least_one_attached_attribute:
            return f"<{self.__class__.__name__}({','.join(field_strings)})>"
        return f"<{self.__class__.__name__} {id(self)}>"


class Tolsysh(Base):
    __tablename__ = "tolsysh"
    sysno: Mapped[str] = mapped_column(primary_key=True)
    sysname: Mapped[str]
    defdir: Mapped[str]
    status: Mapped[str]
    inuser: Mapped[str]
    indate: Mapped[datetime.datetime]
    vssdir: Mapped[str]
    remark: Mapped[str]
    defaultyn: Mapped[str]

    def __repr__(self):
        return self.repr(
            sysno=self.sysno,
            sysname=self.sysname,
            defdir=self.defdir,
            status=self.status,
            inuser=self.inuser,
            indate=self.indate,
            vssdir=self.vssdir,
            remark=self.remark,
            defaultyn=self.defaultyn,
        )


class Tolsysd(Base):
    __tablename__ = "tolsysd"
    sysno: Mapped[str] = mapped_column(primary_key=True)
    trseq: Mapped[int] = mapped_column(primary_key=True)
    apno: Mapped[str]
    apdirectory: Mapped[str]
    status: Mapped[str]
    inuser: Mapped[str]
    indate: Mapped[datetime.datetime]

    def __repr__(self):
        return self.repr(
            sysno=self.sysno,
            trseq=self.trseq,
            apno=self.apno,
            apdirectory=self.apdirectory,
            status=self.status,
            inuser=self.inuser,
            indate=self.indate,
        )
